<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Ledger\BalanceSplit\BalanceSplitService;
use JLPay\Models\Ledger\BalanceSplit\BalanceRefundRequest;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 账本 - 余额退款功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建余额退款请求
 */
function buildBalanceRefundRequest(): BalanceRefundRequest
{
    $request = new BalanceRefundRequest();
    
    // 设置请求参数
    $request->setOrgCode("50720711")
        ->setMchId("849581183510017")
        ->setOutOrderNo("045e1314f7784f46bf9d590dc65c7")
        ->setOutReturnNo("12e3045e13146bf9d590d12c65c11")
        ->setRevMchId("849584307420004")
        ->setAmount("100")
        ->setDescription("分账退回");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 余额退款示例
 */
function balanceRefundDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行余额退款示例");
    
    // 创建配置对象和余额分账服务
    $config = createConfig();
    $balanceSplitService = new BalanceSplitService($config);
    
    // 创建余额退款请求
    $request = buildBalanceRefundRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $balanceSplitService, 
        $request, 
        "余额退款",
        function($service, $request) {
            return $service->refundBalance($request);
        }
    );

    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
}

// =================== 主程序 =====================
if (php_sapi_name() === 'cli') {
    $logger = Logger::getInstance();
    
    // 设置日志级别为INFO
    $logger->setLevel('INFO');
    
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 余额退款示例 开始 =====");
    $logger->info(str_repeat("=", 50));
    balanceRefundDemo();
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 余额退款示例执行完毕 =====");
    $logger->info(str_repeat("=", 50));
} 